﻿using System.Collections.Generic;
using System.Threading.Tasks;
using Aierp.Entities;
using Aierp.Repository;
using Aierp.SystemEntities.System;
using Aierp.Utility;
using Aierp.Utility.Core;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace Aierp.Controllers
{
    [Route("api/[controller]")]
    public class UserRolesController : ControllerBase
    {

        IRepository<Sys_UserRoles> UserRoles { get; set; }
        SysVisitor SysVisitor { get; set; }
        public UserRolesController(IRepository<Sys_UserRoles> userRoles, SysVisitor sysVisitor)
        {
            UserRoles = userRoles;
            SysVisitor = sysVisitor;
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public async Task Get(int id)
        {
            var model = UserRoles.FindById(id);
            //return JSONhelper.ToJson(model);
            if (model == null)
            {
                await this.WriteSpecReasonJson("当前用户尚未分配角色，请分配角色！");
                return;
            }
            await WriteResultJson(model);
        }

        // POST api/values
        [HttpPost]
        public async Task Post(string value)
        {
            //检查用户是否有权限操作
            if (!await CheckUser(SysVisitor)) return;

            ////获取用户对象
            var model = GetModel<Sys_UserRoles>();

            if (model.RoleID==0) await this.WriteSpecReasonJson("保存失败，错误信息如下：角色名称不能为空！");

            var result = UserRoles.Add(model);

            if (result > 0) await this.WriteSucessJson();

            if (result == -9) await this.WriteSpecReasonJson("超级管理员不允许更换角色名称！");
        }
    }
}
